import { useState } from "react";
import {
  listAppMenu,
  delAppMenuResources,
  findMaxSort,
  addAppMenuResources, updateAppMenuResources, getAppMenuResources
} from '@/api/appMenuResources/appMenuResources'

import { Table, Divider, Button, message, Modal, Form, Flex, Space, Typography, Avatar, Badge, Splitter } from "antd";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled, DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons';
import { useThemeToken } from "@/theme/hooks";
import AppMenuForm from "./modules/appMenuForm";
import SelectMenuTree from "./modules/selectMenuTree";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { useRouter, useSearchParams } from "@/router/hooks";
import styled from 'styled-components'
import { m } from "framer-motion";
import { useRef } from "react";


const SliderTrigger = ({ onChange, value }) => {
  const { colorBorder, colorBgBase } = useThemeToken()
  const StyledDiv = styled.div`
  position: absolute;
  width: 20px;
  height: 30px;
  top: 16px;
  left: ${value ? '-19px' : '-1px'};
  text-align: center;
  line-height: 30px;
  border: ${colorBorder} solid 1px;
  background-color: ${colorBgBase};
  border-width: ${value ? '1px 0px 1px 1px' : '1px 1px 1px 0'};
  cursor: pointer;
`
  return (
    <StyledDiv
      onClick={() => onChange(!value)}
    >
      {value ? <DoubleLeftOutlined /> : <DoubleRightOutlined />}
    </StyledDiv >
  )
}

const StyleSelectDeptTree = styled.div`
  .ant-input-search{
    padding-right: 20px;
  }
`

//i18n
const AppMenuDetail = () => {
  useDictionary('resource_type,open_type,route_type,sys_normal_disable'.split(","));
  const { back } = useRouter()
  const searchParams = useSearchParams()
  const [parentNode, setParentNode] = useState()
  const [queryParam, setQueryParam] = useState({
    parentId: '-1'
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const { colorBorder } = useThemeToken();
  const [sliderShow, setSliderShow] = useState(true)
  const menuTreeRef = useRef()
  const addFormRef = useRef()
  const editFormRef = useRef()

  const columns = [
    {
      title: '资源名称',
      dataIndex: 'resourceName'
    },
    {
      title: '资源编码',
      dataIndex: 'resourceCode'
    },
    {
      title: '资源类型',
      dataIndex: 'resourceType',
      render: (text) => (
        <DisplayLabel value={text} type="resource_type" />
      )
    },
    {
      title: 'url请求',
      width: 180,
      dataIndex: 'requestUrl'
    },
    {
      title: '打开方式',
      dataIndex: 'openType',
      render: (text) => (
        <DisplayLabel value={text} type="open_type" />
      )
    },
    {
      title: '加载方式',
      dataIndex: 'routeType',
      render: (text) => (
        <DisplayLabel value={text} type="route_type" />
      )
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      render: (text) => (<Badge status={text == '0' ? 'processing' : 'error'} text={<DisplayLabel value={text} type="sys_normal_disable" />} />)
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '200',
      render: (_, record) => (
        <>
          <ModalForm
            formRef={editFormRef}
            trigger={<a>修改</a>}
            title={'修改应用菜单管理'}
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            request={() => {
              return getAppMenuResources(record.id).then(({ data = {} }) => {
                return { ...data, treeLevel: data.treeLevel + '', routeType: data.routeType + '' }
              })
            }}
            grid={true}
          >
            <AppMenuForm
              formMenu={{
                wantRoot: true,
                rootName: searchParams.get('appName'),
                wrapId: searchParams.get('id'),
                onOk: (_, node) => {
                  editFormRef.current.setFieldsValue({
                    treeLevel: (node.treeLevel || 1) + 1 + '',
                  })
                }
              }} />
          </ModalForm>

          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];


  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-appMenuDetail-listAppMenu', queryParam, page, searchParams.get('appId')],
    queryFn: () => {
      return listAppMenu({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        clientId: searchParams.get('appId'),
        ...queryParam
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
    enabled: !!searchParams.get('appId')
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const saveData = (values) => {
    values.clientId = searchParams.get('appId')
    if (values.id) {
      return updateAppMenuResources(values).then((res) => {
        if (res.code === 200) {
          refetch()
          menuTreeRef.current.refetch()
          message.success('修改成功')
          return true
        }
      })
    } else {
      return addAppMenuResources(values).then((res) => {
        if (res.code === 200) {
          refetch()
          menuTreeRef.current.refetch()
          message.success('新增成功')
          return true
        }
      })
    }
  }

  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    const userNames = row.resourceName || selectedRows.map(d => d.resourceName)
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      content: '当前选中编号为' + userNames + '的数据',
      autoFocusButton: null,
      onOk() {
        return delAppMenuResources(ids)
          .then((res) => {
            if (res.code === 200) {
              onSelectChange([], [])
              menuTreeRef.current.refetch()
              refetch()
              message.success('删除成功')
            }
          })
      },
      onCancel() { },
    });
  };

  const onTreeChange = (value, info) => {
    setQueryParam({
      ...queryParam,
      parentId: value[0] || '-1'
    })

    setParentNode(info.selected ? info.node : undefined)
  }

  return (
    <Splitter style={{ padding: `0 16px`, minHeight: '100%' }}>
      <Splitter.Panel defaultSize={240} min={200} max="70%" collapsible>
        <StyleSelectDeptTree style={{ display: sliderShow ? 'block' : 'none', padding: '16px 10px' }}>
          <SelectMenuTree
            ref={menuTreeRef}
            showSearch
            wantRoot
            rootName={searchParams.get('appName')}
            id={searchParams.get('id')}
            selectedKeys={[queryParam.parentId]}
            onSelect={onTreeChange} />
        </StyleSelectDeptTree>
        {/* <m.div
          style={{ borderRight: `1px solid ${colorBorder}`, flexShrink: 0 }}
          animate={sliderShow ? "open" : "closed"}
          variants={{
            open: {
              width: 220,
              transition: {
                type: "tween",
                duration: 0.3,
              },
            },
            closed: {
              width: 0,
              display: "none",
              transition: {
                type: "tween",
                duration: 0.3,
              },
            },
          }}
        ></m.div> */}
      </Splitter.Panel>
      <Splitter.Panel>
        <Flex flex={1} vertical style={{ padding: '12px 16px', position: 'relative' }}>
          <SliderTrigger value={sliderShow} onChange={setSliderShow} />
          <Flex style={{ padding: '12px 0' }} align="center" justify="space-between">
            <Typography.Title level={4} style={{ paddingLeft: '12px' }}>
              {parentNode?.title || '应用菜单管理'}
            </Typography.Title>
            <Space>
              <ModalForm
                trigger={<Button icon={<PlusOutlined />} type="primary">新增</Button>}
                title="添加应用菜单管理"
                modalProps={{ destroyOnClose: true }}
                onFinish={saveData}
                grid={true}
                request={() => {
                  return findMaxSort(queryParam.parentId).then(res => {
                    return { parentId: queryParam.parentId, treeSort: res?.data, status: '0', hideleft: '1', treeLevel: (parentNode?.treeLevel || 0) + 1 + '' }
                  })
                }}
              >
                <AppMenuForm
                  formRef={addFormRef}
                  formMenu={{
                    wantRoot: true,
                    rootName: searchParams.get('appName'),
                    wrapId: searchParams.get('id'),
                    onOk: (_, node) => {
                      addFormRef.current.setFieldsValue({
                        treeLevel: (node.treeLevel || 1) + 1 + '',
                      })
                    }
                  }} />
              </ModalForm>
              {selectedRowKeys.length > 0 && <Button danger onClick={deleteConfirm}>批量删除</Button>}
              <Button onClick={back}>返回</Button>
            </Space>
          </Flex>

          <Table
            rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
            columns={columns}
            rowKey={(record) => record.id}
            loading={isFetching}
            dataSource={tableData?.list || []}
            pagination={{
              current: page.pageNo,
              pageSize: page.pageSize,
              total: tableData?.total,
              onChange: (pageNo, pageSize) => {
                setPage({ pageNo, pageSize })
              }
            }}
          />
        </Flex>
      </Splitter.Panel>
    </Splitter>
  );
};


export default AppMenuDetail;
